import sympy as sp


def compute_gradient():
    # 定义符号变量
    x, y = sp.symbols('x y')

    # 定义函数表达式
    u = x * y * (1 - x/2) * (1 - y) * sp.exp(x + y)

    # 计算梯度（偏导数列表）
    grad_u = [sp.diff(u, var) for var in [x, y]]

    # 简化梯度表达式
    grad_u_simplified = [sp.simplify(g) for g in grad_u]

    # 打印结果
    print("原函数 u(x, y):")
    sp.pprint(u)

    print("\n梯度 ∇u(x, y):")
    for i, var in enumerate(['x', 'y']):
        print(f"∂u/∂{var} =")
        sp.pprint(grad_u_simplified[i])

    # 返回符号表达式
    return u, grad_u_simplified


# 执行计算
u, grad = compute_gradient()
